package com.jcbase.controller.sys;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcbase.core.BaseConstance;
import com.jcbase.core.auth.anno.RequiresPermissions;
import com.jcbase.core.controller.JCBaseController;
import com.jcbase.core.model.Condition;
import com.jcbase.core.model.Operators;
import com.jcbase.core.util.CommonUtils;
import com.jcbase.core.util.DESUtils;
import com.jcbase.core.util.DateUtils;
import com.jcbase.core.util.JqGridModelUtils;
import com.jcbase.model.RisebdCoupon;
import com.jcbase.model.RisebdCouponMember;
import com.jcbase.model.RisebdCouponRule;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;

/**
 * @category 优惠券规则
 * 
 * @author yiz
 * @date 2016年8月10日 下午7:16:45
 * @version 1.0.0 
 * @copyright pycredit.cn 
 */
public class CouponRuleController extends JCBaseController {
	private static final Logger logger = LoggerFactory.getLogger(CouponRuleController.class);

	@RequiresPermissions(value = { "/sys/couponRule" })
	public void index() {
		this.renderJsp("coupon_rule_index.jsp");
	}

	@RequiresPermissions(value = { "/sys/couponRule/rollback" })
	@Before(Tx.class)
	public void rollback() {
		String id = getPara("id");
		Integer status = getParaToInt("status");
		Map<String, Object> mapData = new HashMap<String, Object>();
		if (id != null) {
			RisebdCouponRule risebdCouponRule = RisebdCouponRule.me.getById(id);
			if (null != risebdCouponRule) {
				boolean flag = RisebdCouponRule.me.updateStatus(risebdCouponRule, status);
				//删除优惠券，改变状态
				RisebdCoupon.me.updateRoleStatus(id, status);
				RisebdCouponMember.me.updateRuleStatus(id, status);
				if (flag) {
					mapData.put("code", "success");
					mapData.put("result", "操作成功！！");
				} else {
					mapData.put("code", "fail");
					mapData.put("result", "操作失败！！");
				}
			}
		}
		renderJson(mapData);
	}

	@RequiresPermissions(value = { "/sys/couponRule/save" })
	public void add() {
		String id = getPara("id");
		logger.info("请求参数id=" + id);
		if (id != null) {
			RisebdCouponRule risebdCouponRule = RisebdCouponRule.me.getById(id);
			setAttr("couponRule", risebdCouponRule);
		}
		this.renderJsp("coupon_rule_add.jsp");
	}

	@RequiresPermissions(value = { "/sys/couponRule/save" })
	public void getStatus() {
		String id = getPara("id");
		logger.info("请求参数id=" + id);
		Map<String, Object> mapData = new HashMap<String, Object>();
		if (id != null) {
			RisebdCouponRule risebdCouponRule = RisebdCouponRule.me.getById(id);
			if (null != risebdCouponRule) {
				mapData.put("status", risebdCouponRule.getStatus());
			}
		}
		renderJson(mapData);
	}

	@RequiresPermissions(value = { "/sys/couponRule/save" })
	@Before(Tx.class)
	public void updateStatus() {
		String id = getPara("id");
		Integer status = getParaToInt("status");
		logger.info("请求参数id={},status={}", id, status);
		Map<String, Object> mapData = new HashMap<String, Object>();
		if (id != null) {
			RisebdCouponRule risebdCouponRule = RisebdCouponRule.me.getById(id);
			if (null != risebdCouponRule) {
				boolean flag = RisebdCouponRule.me.updateStatus(risebdCouponRule, status);
				if (flag) {
					mapData.put("code", "success");
					mapData.put("result", "操作成功！！");
				} else {
					mapData.put("code", "fail");
					mapData.put("result", "操作失败！！");
				}
			}
		}
		renderJson(mapData);
	}

	@RequiresPermissions(value = { "/sys/couponRule/save" })
	public void create() {
		String id = getPara("id");
		logger.info("请求参数id=" + id);
		Map<String, Object> mapData = new HashMap<String, Object>();

		if (id != null) {
			RisebdCouponRule risebdCouponRule = RisebdCouponRule.me.getById(id);
			//根据规则生成优惠券并更新规则状态
			if (null != risebdCouponRule) {
				Integer status = risebdCouponRule.getStatus();
				if (0 != status) {
					mapData.put("errcode", 1);
					mapData.put("msg", "该优惠券规则状态不允许操作！");
					this.renderJson(mapData);
					return;
				}
				Date couponStartTime = risebdCouponRule.getCouponStartTime();//开始时间
				Date couponEndTime = risebdCouponRule.getCouponEndTime();//结束时间
				//当当前时间大于开始时间或者结束时间时不可以在生成优惠券
				Date nowDate = DateUtils.getNowDateTime();
				long checkStartEndTime = DateUtils.compareIntervalDay(couponStartTime, couponEndTime);
				if (checkStartEndTime < 0) {
					mapData.put("errcode", 1);
					mapData.put("msg", "规则开始时间与结束时间不合法!");
					this.renderJson(mapData);
					return;
				}
				long checkStartNowTime = DateUtils.compareIntervalDay(couponStartTime, nowDate);//2-4 //3
				long checkEndNowTime = DateUtils.compareIntervalDay(couponEndTime, nowDate);
				if (checkStartNowTime > 0) {
					mapData.put("errcode", 1);
					mapData.put("msg", "开始时间已大于当前时间!");
					this.renderJson(mapData);
					return;
				}
				if (checkEndNowTime > 0) {
					mapData.put("errcode", 1);
					mapData.put("msg", "当前时间已大于结束时间!");
					this.renderJson(mapData);
					return;
				}
				//开始生成优惠券
				try {
					createCoupon(risebdCouponRule);
					mapData.put("errcode", 0);
					mapData.put("msg", "已生成优惠券，请在优惠券管理查看详情！");
					this.renderJson(mapData);
					return;
				} catch (Exception e) {
					logger.error("生成失败e={}", e);
					mapData.put("errcode", 1);
					mapData.put("msg", "生成失败");
					this.renderJson(mapData);
					return;
				}
			}
		}
		mapData.put("errcode", 1);
		mapData.put("msg", "不存在此优惠券规则！");
		this.renderJson(mapData);
	}

	public void getListData() {
		String title = this.getPara("title");
		Set<Condition> conditions = new HashSet<Condition>();
		if (CommonUtils.isNotEmpty(title)) {
			conditions.add(new Condition("title", Operators.LIKE, title));
		}
		conditions.add(new Condition("status", Operators.NOT_EQ, 5));
		Page<RisebdCouponRule> pageInfo = RisebdCouponRule.me.getPage(getPage(), this.getRows(), conditions,
				this.getOrderby());
		this.renderJson(JqGridModelUtils.toJqGridView(pageInfo));
	}

	@RequiresPermissions(value = { "/sys/couponRule/save" })
	public void saveRes() {
		String id = getPara("id");
		String title = getPara("title");
		Integer type = getParaToInt("type");
		Integer conpon_form = getParaToInt("conpon_form", 0);
		String coupon_amountStr = getPara("coupon_amount", "0");
		Double coupon_amount = Double.valueOf(coupon_amountStr);
		Long coupon_num = getParaToLong("coupon_num");
		Integer get_times = getParaToInt("get_times", 0);
		String limit_amountStr = getPara("limit_amount", "0");
		Double limit_amount = Double.valueOf(limit_amountStr);
		Integer status = getParaToInt("status", 0);
		String start_timingValue = getPara("start_timing");
		Date start_timing = DateUtils.parseDate(start_timingValue);

		Date coupon_start_time = getParaToDate("coupon_start_time");

		String coupon_end_timeValue = getPara("coupon_end_time");
		Date coupon_end_time = DateUtils.parseDate(coupon_end_timeValue + " 23:59:59");
		String mark = getPara("mark");
		Map<String, Object> mapData = new HashMap<String, Object>();
		if (CommonUtils.isEmpty(id) && (1 == type || 2 == type || 3 == type)) {
			boolean hasCouponRuleByType = RisebdCouponRule.me.hasCouponRuleByType(type);
			if (hasCouponRuleByType) {
				mapData.put("code", "fail");
				mapData.put("result", "操作失败，已存在此类型的规则，不可新增!");
				this.renderJson(mapData);
				return;
			}
		}
		int result = RisebdCouponRule.me.save(id, title, type, conpon_form, coupon_amount, coupon_num, get_times,
				limit_amount, status, start_timing, coupon_start_time, coupon_end_time, mark);
		mapData.put("code", "success");
		if (result == 1) {
			mapData.put("result", "添加成功！！");
		} else if (result == 2) {
			mapData.put("result", "编辑成功！！");
		}
		this.renderJson(mapData);
	}

	@RequiresPermissions(value = { "/sys/couponRule/delete" })
	public void delete() {
		String id = getPara("id");
		boolean result = RisebdCouponRule.me.deleteById(id);
		Map<String, Object> mapData = new HashMap<String, Object>();
		mapData.put("code", "success");
		if (result) {
			mapData.put("result", "删除成功！！");
		} else {
			mapData.put("result", "删除失败！！");
		}
		this.renderJson(mapData);
	}

	@Before(Tx.class)
	private void createCoupon(RisebdCouponRule risebdCouponRule) throws Exception {
		String id = risebdCouponRule.getId();
		Integer couponType = risebdCouponRule.getType();
		Long couponNum = risebdCouponRule.getCouponNum();
		if (couponNum == null || couponNum == 0) {
			//当设置数量为0时，只改变状态
			boolean uFlag = RisebdCouponRule.me.updateStatus(risebdCouponRule, 1);
			logger.info("修改优惠券规则状态uFlag={}", uFlag);
		} else {
			List<String> couponNos = new ArrayList<>();
			String couponNo = null;
			for (int i = 0; i < couponNum; i++) {
				Random random = new Random();
				DESUtils desUtils = new DESUtils(BaseConstance.DES_COUPON_KEY);
				String result = desUtils.encryptString(Calendar.getInstance().getTime() + (random.nextDouble() + ""));
				couponNo = "YHQ" + result.substring(result.length() - 12, result.length());

				RisebdCoupon risebdCoupon = RisebdCoupon.me.getCouponByNoType(couponNo, couponType);
				if (null == risebdCoupon) {
					couponNos.add(couponNo);
				}
			}
			boolean uFlag = RisebdCouponRule.me.updateStatus(risebdCouponRule, 1);
			logger.info("修改优惠券规则状态uFlag={}", uFlag);
			int result = RisebdCoupon.me.batchSave(couponNos, id, 0, couponType);
			logger.info("保存结果result={}", result);
		}
	}
}
